//
//  SearchTableViewController.m
//  Mango
//
//  Created by lanou3g on 16/5/12.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "SearchTableViewController.h"
#import "HotSearchView.h"
#import "LeftModel.h"
#import "LeftModelCell.h"
#import "SearchListController.h"
#import "DBManager.h"
#define searchIndex_url @"http://api.app.happyjuzi.com/search/index"


@interface SearchTableViewController ()<UISearchBarDelegate,HotSearchViewDelegate>
@property (nonatomic, strong) NSMutableArray *keywords;

@property (nonatomic, strong) NSMutableArray *searchHistory;
@property (nonatomic, strong) HotSearchView *hotSearchView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, copy) NSString *currentSkinModel;//夜间模式
@end

@implementation SearchTableViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.keywords = [NSMutableArray new];//热门搜索
    self.hotSearchView = [[HotSearchView alloc]initWithFrame:CGRectMake(0, 0, 0, 200)];
    self.hotSearchView.delegate = self;
    self.tableView.tableFooterView = self.hotSearchView;
   
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 0, 40)];
    self.tableView.tableHeaderView = self.searchBar;
    self.searchBar.placeholder = @"搜索你感兴趣的内容";
    self.searchBar.delegate = self;
    [self.searchBar becomeFirstResponder];
    [self.searchBar setShowsCancelButton:YES animated:YES];
    [self loadKeywordData];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.searchHistory = [[DBManager shareManager]selectAllSearchHistory].mutableCopy;//搜索历史
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
    [self.tableView reloadData];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --private Method--更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        self.tableView.backgroundColor = [UIColor blackColor];
        [self.hotSearchView updateToNightSkinMode];
    } else {//日间模式
//        self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:1];
//        [self.hotSearchView updateToDaySkinMode];
    }
    [self.tableView reloadData];
}


#pragma mark - HotSearchViewDelegate
- (void)hotsSearchViewdidClickButton:(NSString *)title {
    self.searchBar.text = title;
    if (![[DBManager shareManager]hasSave:title]) {
        [[DBManager shareManager]saveSearchHistory:title];
    }
    SearchListController *listVC = [[SearchListController alloc]init];
    listVC.keyword = title;
    [self.navigationController pushViewController:listVC animated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
//    [self.navigationController popViewControllerAnimated:YES];
}

//请求热门搜索数据
- (void)loadKeywordData {
   NSDictionary *parmar = @{@"uid":@"3971092394255935",@"res":@"1080x1920",@"ver":@"2.11",@"pf":@"android",@"channel":@"yingyongbao",@"accesstoken":@"e43c576b3de11eeeb758223cb56752c1",@"net":@"wifi"};
    [self loadDataFromServerWithUrl:searchIndex_url Parmar:parmar];
}

//请求网络数据
- (void)loadDataFromServerWithUrl:(NSString *)url Parmar:(NSDictionary *)parmar {
    [[AFHTTPSessionManager manager]GET:url parameters:parmar progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
     [self parserKeywordWithDict:responseObject];//解析热门搜索
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

//解析热门搜索
- (void)parserKeywordWithDict:(NSDictionary *)responseObject {
    NSDictionary *dataDict = responseObject[@"data"];
    for (NSDictionary *dict in dataDict[@"list"]) {
        NSString *keyword = dict[@"keyword"];
        [self.keywords addObject:keyword];
    }
    self.hotSearchView.titles = self.keywords;
}


//开始搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    SearchListController *listVC = [[SearchListController alloc]init];
    listVC.keyword = self.searchBar.text;
    if (self.searchBar.text.length > 0 && ![[DBManager shareManager]hasSave:self.searchBar.text]) {
        //插入数据库之
        [[DBManager shareManager]saveSearchHistory:self.searchBar.text];
    }
    [self.navigationController pushViewController:listVC animated:YES];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    
    return self.searchHistory.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.searchHistory[indexPath.row];
#pragma mark --private Method--更新皮肤模式
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
        cell.textLabel.textColor = [UIColor grayColor];
        cell.contentView.backgroundColor = [UIColor colorWithRed:42/255.0 green:39/255.0 blue:43/255.0 alpha:1.0];
    }else {
        cell.textLabel.textColor = [UIColor blackColor];
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *history = self.searchHistory[indexPath.row];
        [self.searchHistory removeObject:history];
        [[DBManager shareManager]deleteSearchHistory:history];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationFade)];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchListController *searchListVC = [[SearchListController alloc]init];
    searchListVC.keyword = self.searchHistory[indexPath.row];
    [self.navigationController pushViewController:searchListVC animated:YES];
}
@end
